#!/bin/bash

## set _CONDOR_IHEP_JOB_ID
_CONDOR_IHEP_JOB_ID=`/bin/grep -E '^GlobalJobId ' $_CONDOR_JOB_AD | /bin/awk -F'#' '{print $2}'`
export _CONDOR_IHEP_JOB_ID=$_CONDOR_IHEP_JOB_ID

## The handler of signals
trap stop_user_job 2 3 15
stop_user_job() {
    #echo "Job ${_CONDOR_IHEP_JOB_ID} is stopped by signal"
    kill -TERM $JobPid
}

## execute user's job with maximum (JobLimit) wall time
JobWallTime=`/bin/grep -E '^WallTime ' $_CONDOR_JOB_AD | /bin/awk -F'"' '{print $2}'`
JobLimit=360000  # 100 hours
if [[ "$JobWallTime" == "long" ]]; then
    JobLimit=2592000  # 30 days
fi

## keep the virtual memory used by each job
VMLimit=100000000 # 100GB
ulimit -v $VMLimit

UserExe=$1
shift
/usr/bin/timeout $JobLimit ${UserExe} "$@" &

## Capture the pid of the job to kill later, if needed
JobPid=$!
## Wait for the job to exit of own accord
wait $JobPid
ExitCode=$?
if [ $ExitCode -eq 124 ]; then
    echo "Job is KILLED: exceeds the 100 hours time limit" >&2
fi

exit $ExitCode
